
export default {
	data () {
		return {
			im_info: {},
			messages: [],
			prev_id: null,
			is_done: false,
			loading: false,
			send_loading: false,
		}
	},
	computed: {
		user_info () {
			return this.$store.state.user.user
		}
	},
	watch: {
		user_info (new_value, old_value) {
			if (new_value.hasOwnProperty("id") && old_value.hasOwnProperty("id")) {
				if (new_value.id != old_value.id) {
					this.login_im()
				}
			} else if (!new_value.hasOwnProperty("id") && old_value.hasOwnProperty("id")) {
				this.sign_out();
			} else if (new_value.hasOwnProperty("id") && !old_value.hasOwnProperty("id")) {
				this.login_im()
			}
		},
		'$store.state.system.message' (value) {
			if (value != null) {
				value.conversationType = this.$TIM.TYPES.CONV_C2C
				let message = this.$tim.createCustomMessage(value);
				// 3. 发送消息
				let promise = this.$tim.sendMessage(message);
				promise.then(function (imResponse) {
					// 发送成功
					console.log(imResponse);
				}).catch(function (imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
			}
		}
	},
	methods: {
		init () {
			if (this.user_info.hasOwnProperty("id")) {
				this.login_im()
			}
			// 监听初始化接口事件
			let that = this
			this.$tim.on(this.$TIM.EVENT.SDK_READY, function (event) {
				// 收到离线消息和会话列表同步完毕通知，接入侧可以调用 sendMessage 等需要鉴权的接口
				// event.name - TIM.EVENT.SDK_READY
				that.updateIm()
				that.getChatList()
				return "success"
			});


			// 监听新消息接口事件
			this.$tim.on(this.$TIM.EVENT.MESSAGE_RECEIVED, function (event) {
				// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
				// event.name - TIM.EVENT.MESSAGE_RECEIVED
				// event.data - 存储 Message 对象的数组 - [Message]
				// console.log(event, 1122)
				let data = event.data[0]

				if (data.conversationID == that.contacters[that.choose_user].conversationID) {
					that.readMessage(that.contacters[that.choose_user].userProfile.userID)
					that.messages.push(data)
					that.$nextTick(() => {
						let ref = that.$refs.chat
						ref && (ref.scrollTop = ref.scrollHeight)
					})
				}
			});


			// 监听掉线接口事件
			this.$tim.on(TIM.EVENT.KICKED_OUT, function (event) {
				// 收到被踢下线通知
				// event.name - TIM.EVENT.KICKED_OUT
				// event.data.type - 被踢下线的原因，例如 :
				//   - TIM.TYPES.KICKED_OUT_MULT_ACCOUNT 多实例登录被踢
				//   - TIM.TYPES.KICKED_OUT_MULT_DEVICE 多终端登录被踢
				//   - TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED 签名过期被踢（v2.4.0起支持）。
			});
		},

		login_im () {
			let that = this
			this.$request.get("/auth/imtoken").then((res) => {
				let promise = this.$tim.login({ userID: this.user_info.id + "", userSig: res.sign });
				promise.then(function (imResponse) {
					that.im_info = imResponse
					if (imResponse.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录
					}
				}).catch(function (imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
				});
			})
		},
		updateIm () {
			let promise = this.$tim.updateMyProfile({
				nick: this.user_info.name,
				avatar: this.user_info.avatar,
			});
			promise.then(function (imResponse) {
				console.log(imResponse.data, 'update im'); // 更新资料成功
			}).catch(function (imError) {
				console.warn('updateMyProfile error:', imError); // 更新资料失败的相关信息
			});
		},
		sign_out () {
			let promise = this.$tim.logout();
			promise.then(function (imResponse) {
				console.log(imResponse.data); // 登出成功
			}).catch(function (imError) {
				console.warn('logout error:', imError);
			});

		},
		getChatList () {
			let that = this
			let promise = this.$tim.getConversationList();
			promise.then(function (imResponse) {
				// 全量的会话列表，用该列表覆盖原有的会话列表
				that.contacters = imResponse.data.conversationList;
				that.$store.state.system.contacters = that.contacters
				// 从云端同步会话列表是否完成
				const isSyncCompleted = imResponse.data.isSyncCompleted;
				if (that.contacters[0] && that.contacters[0].userProfile) {
					that.getChatMessage(that.contacters[0].userProfile.userID)

				}
			}).catch(function (imError) {
				// 获取会话列表失败的相关信息
				console.warn('getConversationList error:', imError);
			});
		},
		getChatMessage (user_id) {
			let that = this
			that.readMessage(user_id)
			let promise = this.$tim.getMessageList({ conversationID: 'C2C' + user_id });
			promise.then(function (imResponse) {
				that.messages = imResponse.data.messageList; // 消息列表。
				console.log(that.messages, 'that.messages')
				that.prev_id = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				that.is_done = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
				that.$nextTick(() => {
					let ref = that.$refs.chat
					ref && (ref.scrollTop = ref.scrollHeight)
				})

				console.log('msg',that.messages)

			});
		},
		send (user_id) {
			let that = this
			let message = this.$tim.createTextMessage({
				to: '' + user_id,
				conversationType: that.$TIM.TYPES.CONV_C2C,
				// 消息优先级，用于群聊。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息
				// priority: TencentCloudChat.TYPES.MSG_PRIORITY_NORMAL,
				payload: {
					text: that.message
				},
				// 如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
				needReadReceipt: false
				// 消息自定义数据（云端保存，会发送到对端，程序卸载重装后还能拉取到）
				// cloudCustomData: 'your cloud custom data'
			});
			that.send_loading = true
			// 2. 发送消息
			let promise = this.$tim.sendMessage(message);
			promise.then(function (imResponse) {
				// 发送成功
				that.message = ''
				if (imResponse.code == 0) {
					that.messages.push(imResponse.data.message)
				}
				that.$nextTick(() => {
					let ref = that.$refs.chat
					ref && (ref.scrollTop = ref.scrollHeight)
				})
			}).catch(function (imError) {
				// 发送失败
				console.warn('sendMessage error:', imError);
			}).finally(() => {
				that.send_loading = false

			})

		},
		readMessage (user_id) {
			// 将某会话下所有未读消息已读上报
			let promise = this.$tim.setMessageRead({ conversationID: 'C2C' + user_id });
			promise.then(function (imResponse) {
				// 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
			}).catch(function (imError) {
				// 已读上报失败
				console.warn('setMessageRead error:', imError);
			});
		},
		loadingMore (user_id) {
			let that = this
			that.loading = true
			let promise = this.$tim.getMessageList({ conversationID: 'C2C' + user_id, nextReqMessageID: this.prev_id });
			promise.then(function (imResponse) {
				that.messages = imResponse.data.messageList.concat(that.messages); // 消息列表。
				that.prev_id = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				that.is_done = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
			}).catch(function (imError) {
				// 发送失败
				console.warn('sendMessage error:', imError);
			}).finally(() => {
				that.loading = false
			})

		},
		// infiniteScroll () {
		// 	console.log(2222)
		// }
	}
}